package com.tyt.lelan.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;



public class Net {

	private static Net net;

	public static Net getInstance() 
	{
		if (net == null) 
		{
			net = new Net();
		}
		return net;
	}

	public String get(String mURL) throws Exception 
	{
		String resultString = null;
		URL url ;
		try {
			url = new URL(mURL);
			InputStream is =url.openStream();
			BufferedReader buffreader = new BufferedReader(new InputStreamReader(url.openStream()));
			String encoding = getXMLEncoding(buffreader);
			buffreader.close();
			resultString = readstream(is,encoding);
			if(resultString==null)
				throw new Exception("can't connect the network");
			else
				return resultString.toString();
		}catch (Exception e) {
			throw e;
		}
	}
	

	private String getXMLEncoding(BufferedReader inbuff ) throws Exception {
		// TODO Auto-generated method stub
		String line =	inbuff.readLine();
		if(line.toLowerCase().contains("xml")){
			int start =line.indexOf("encoding=");
			int end = line.indexOf("?>")-1;
			String encoding = line.substring(start+10, end);
			Log.v("编码", encoding);
			return encoding;
		}
		else throw new Exception("Not XML");
	}

	private String readstream(InputStream in,String encoding) throws IOException 
	{
		StringBuffer resultString = new StringBuffer() ;
			BufferedReader inbuff = new BufferedReader(new InputStreamReader(in,encoding));
			String line = "";
			while ((line = inbuff.readLine()) != null){
				resultString.append('\n');
				resultString.append(line);
			}
			inbuff.close();
		return resultString.toString();
	}

}
